import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/ChooserBox.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyInput.dart';
import 'package:hitutor/Widget/MyPage.dart';

import '../../../Util/Global.dart';
import 'DistributingSuccess.dart';

class DistributingClass extends StatefulWidget {
  dynamic oldLessonName; //舊課程名稱，配課成功後需要顯示
  int changeRecords; //配課堂數 分母 （最大值）
  dynamic purchaseOrderId; //選擇的訂單編號
  dynamic unitPrize; //選取的訂單課程單價

  DistributingClass({required this.purchaseOrderId, this.unitPrize, required this.oldLessonName, required this.changeRecords});

  @override
  State<StatefulWidget> createState() {
    return _DistributingClass();
  }
}

class _DistributingClass extends State<DistributingClass> {
  List<dynamic> lessonList = [];
  dynamic lesson = {};
  TextEditingController controller = TextEditingController();

  // priceId  確認配課使用
  chooseClass() {
    showWheelDialog2(context, "", lessonList, "lessonName", (i) {
      lesson = lessonList[i];
      setState(() {});
    });
  }

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getCanDistributingClass();
    });
    super.initState();
  }

  getCanDistributingClass() {
    HttpGo(context).get("/Lesson/GetAssignLessonList?purchaseOrderId=${widget.purchaseOrderId}&unitPrize=${widget.unitPrize}", {}, (data) {
      lessonList = data["lessonList"];
    }, (code, error) => showToast(error));
  }

  confirmDistributing() {
    if(lesson["priceId"]==null){
      showToast("請選擇配課課程");
      return;
    }
    String count = controller.text;
    if (count.isEmpty) {
      showToast("請輸入配課堂數");
      return;
    }
    int count2 = int.parse(count);
    if (count2 < 1) {
      showToast("配課堂數不能為0");
      return;
    }
    if (count2 > widget.changeRecords) {
      showToast("配課堂數不能大於${widget.changeRecords}");
      return;
    }
    HttpGo(context).post("/Lesson/ChangeLesson", {
      "fromPurchaseOrderId": widget.purchaseOrderId,
      "toLessonId": lesson["priceId"],
      "fromLessonCount": count2,
      "toLessonCount": count2,
    }, (data) {
      Global.myOrderKey.currentState?.getOrderData();
      if (data["payUrl"] != null) {
        PageUtil().launchURL(data["payUrl"]);
      }
      PageUtil().openReplace(
          context,
          DistributingSuccess(
            newLessonName: lesson["lessonName"],
            newLessonCount: count2,
            oldLessonName: widget.oldLessonName,
            oldLessonCount: widget.changeRecords,
          ));
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    return MyPage(
        "配課",
        Container(
          child: Column(children: [
            ChooserBox(lesson["lessonName"] ?? "", margin: EdgeInsets.all(12), onTap: chooseClass),
            Row(mainAxisAlignment: MainAxisAlignment.end, children: [
              Text("配課堂數", style: TextStyle(color: MyColor.C7D, fontWeight: FontWeight.bold)),
              Container(
                  height: 28,
                  width: 52,
                  margin: EdgeInsets.fromLTRB(8, 0, 8, 0),
                  padding: EdgeInsets.fromLTRB(4, 0, 4, 0),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(4)),
                      border: Border.all(width: 1, color: MyColor.C9)),
                  child: NormalInput(inputType: NormalInput.Number, fontColor: MyColor.C7D, controller: controller)),
              Text("/ ${widget.changeRecords}堂", style: TextStyle(color: MyColor.C7D, fontWeight: FontWeight.bold)),
              Container(width: 16)
            ]),
            Expanded(child: Container()),
            Container(height: 1, color: Color(0xffdee2e6), margin: EdgeInsets.fromLTRB(0, 8, 0, 16)),
            Row(mainAxisSize: MainAxisSize.min, children: [
              TextBtn("取消", height: 36, width: 120, style: TextStyle(color: MyColor.Orange), onTap: () {
                PageUtil().back(context);
              }),
              Button("進行配課", height: 36, bgColor: MyColor.Orange, width: 120, radius: 4, onTap: confirmDistributing)
            ]),
            Container(height: 16)
          ]),
        ));
  }
}
